﻿using AutoMapper;
using MediatR;
using S.RBAC.Api.Application.Command.DepartmentCommand;
using S.RBAC.Domain.Model;
using S.RBAC.Infrastructure.Interface;

namespace S.RBAC.Api.Application.CommandHandlers.DepartmentHandler
{
    public class DepartmentCreateCommandHandler : IRequestHandler<DepartmentCreateCommand, int>
    {
        protected readonly IDepartmentRepository _department;
        protected readonly IMapper _mapper;

        public DepartmentCreateCommandHandler(IDepartmentRepository department, IMapper mapper)
        {
            _department = department;
            _mapper = mapper;
        }

        public async Task<int> Handle(DepartmentCreateCommand request, CancellationToken cancellationToken)
        {
            var departInfo = _mapper.Map<Department>(request);

            var info = await _department.GetListDepartment(t => t.DepartCode == departInfo.DepartCode || t.DepartName == departInfo.DepartName);

            var list = info.FirstOrDefault();

            if (info.Count != 0)
            {
                return 0;
            }

            departInfo.CreateBy = "孔令琪";
            departInfo.CreateDate = DateTime.Now;
            departInfo.UpdateBy = null;
            departInfo.UpdateDate = null;
            departInfo.IsDel = false;

            return await _department.AddDepartment(departInfo);
        }
    }
}
